/*
 * File Name：ListenSpeakUtil.java
 * Copyright：Copyright 2008-2015 CiWong.Inc. All Rights Reserved.
 * Description： ListenSpeakUtil.java
 * Modify By：pla-gysu
 * Modify Date：2015年1月22日
 * Modify Type：Add
 */
package com.ciwong.epaper.modules.epaper.util;

import android.content.Context;
import android.text.TextUtils;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.ModuleInfo;
import com.ciwong.epaper.modules.epaper.bean.OptionDetail;
import com.ciwong.epaper.modules.epaper.bean.OptionInfo;
import com.ciwong.epaper.modules.epaper.bean.QuestionRule;
import com.ciwong.epaper.modules.epaper.bean.QuestionScore;
import com.ciwong.epaper.modules.epaper.bean.Questions;
import com.ciwong.epaper.modules.epaper.bean.ResourceDetail;
import com.ciwong.epaper.modules.reciteWords.dbreciteword.BaseDBManager;
import com.ciwong.epaper.util.SerializableManager;

import java.math.BigDecimal;
import java.util.List;

/**
 * 听说模考工具类
 *
 * @author pla-gysu
 * @version ciwong v.1.0 2015年1月22日
 * @since ciwong v.1.0
 */
public class ListenSpeakUtil {

    /**
     * 匹配是否打分
     */
    public static final String JSGF = "#JSGF";

    public interface IRefreshDoRecord {
        void refreshDoRecord(List<Boolean> isDoRecords);
    }

    /**
     * 格式化作业用时秒数
     *
     * @param context
     * @param workLong
     * @return
     */
    public static String formatWorkLong(Context context, int workLong) {
        long minute = workLong % 3600 / 60;
        long second = workLong % 60;
        return context.getString(R.string.work_long_show, minute, second);
    }

    /**
     * 格式化作业用时秒数
     *
     * @param context
     * @param remainingTime
     * @return
     */
    public static String formatNetSpeed(Context context, int speed, int remainingTime, boolean isShowRemainTime) {
        long minute = remainingTime % 3600 / 60;
        long second = remainingTime % 60;

        if (isShowRemainTime) {
            if (minute > 0) {
                return context.getString(R.string.net_speed_show_min, speed, minute, second);
            } else {
                return context.getString(R.string.net_speed_show_second, speed, second);
            }
        } else {
            return context.getString(R.string.net_speed_show_second2, speed);
        }


    }

    /**
     * 给数据加上<body/>标签
     *
     * @param text
     * @return
     */
    public static String addHtmlHead(String text) {
        String head = "<html>\n" + "<head>\n"
                + "    <meta charset=\"utf-8\" />\n"
                + "    <meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0\" />\n"
                + "    <style type=\"text/css\">\n"
                + "        html { -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; line-height: 1.428571429; font-size: 0.9em; }\n"
                + "        body { -webkit-touch-callout: none; font-family: \"Helvetica Neue\",Helvetica,\"Hiragino Sans GB\",\"Microsoft YaHei\",Arial,sans-serif; background-color: #F7F7F7; line-height: inherit; padding:8px; }\n"
                + "        .container { width: 100%; }\n"
                + "        table { border: 1px solid #dddddd; width: 100%; position: relative; }\n"
                + "        table { background-color: white; border-collapse: collapse;}\n"
                + "        table > tbody > tr > td { border: 1px solid #dddddd; padding: 8px; line-height: 1.428571429; font-size: 0.9em;  }\n"
                + "        .table-container { width: 100%; overflow-y: auto; _overflow: auto; margin: 0 0 1em; }\n"
                + "        .table-container::-webkit-scrollbar { -webkit-appearance: none; width: 14px; height: 14px; }\n"
                + "        .table-container::-webkit-scrollbar-thumb { border-radius: 8px; border: 3px solid #fff; background-color: rgba(0, 0, 0, .3); }\n"
                + "        .table-container table > tbody > tr > td {white-space: nowrap; }\n"
                + "    </style>\n" + "</head>\n" + "\n" + "<body>\n"
                + "    <div class=\"container\">";
        String end = "</div></body></html>";
        return head + parseHtmlText(text) + end;
    }

    public static String regular = "\\{\\#blank\\#\\}(\\d*)\\{\\#\\/blank\\#\\}";

    /**
     * 转化html文本
     *
     * @param text
     * @return
     */
    public static String parseHtmlText(String text) {

        String value = "<span style=\"border-bottom:1px solid #333;padding: 0 10px 0 10px;min-width: 50px;\">$1</span>";
        return text.replaceAll("\n", "<br>").replaceAll(regular, value);
    }

    public static String parseHtmlText2(String text) {
        String value = "<span style=\"border-bottom:1px  #333;padding: 0 10px 0 10px;min-width: 50px;\">$1</span>";
        return text.replaceAll("\n", "<br>").replaceAll(regular, value);
    }

    /**
     * 模式
     */
    public class LsMode {
        /**
         * 自主练习
         */
        public static final int OWN_PRACTISE = 1;
        /**
         * 作业模式
         */
        public static final int HOME_WORK_MODE = 2;
        /**
         * 重做某题模式
         */
        public static final int RETRY_MODE = 3;
        /**
         * 主观题模式
         */
        public static final int SUBJECTIVE_MODE = 4;

    }

    /**
     * 固定音频播放地址
     */
    public static class SoundUrl {
        /**
         * 开始考试
         */
        public static final int SOUND_START_EXAM = R.raw.start_exam;

        /**
         * 开始答题
         */
        public static final int SOUND_START_ANSWER = R.raw.start_answer;

        /**
         * 开始录音
         */
        public static final int SOUND_START_AUDIO = R.raw.start_audio;

        /**
         * 录音结束
         */
        public static final int SOUND_END_AUDIO = R.raw.end_audio;

        /**
         * 考试结束
         */
        public static final int SOUND_END_EXAM = R.raw.end_exam;


        /**
         * 答题结束
         */
        public static final int SOUND_END_ANSWER = R.raw.end_answer;
    }

    /**
     * 当前状态
     */
    public enum State {
        START, // 考试开始
        BIG_QUESTION_STEM, // 播放大题题干音频
        LOOK_SMALL_QUESTION, // 小题阅题
        SMALL_QUESTION_STEM, // 播放小题音频
        READY_SMALL_QUESTION, // 小题准备
        LOOK_CHILD_QUESTION, // 子题阅题
        CHILD_QUESTION_STEM, // 播放子题音频
        READY_CHILD_QUESTION, // 子题准备
        ANSWER, // 答题/录音
        END_AUDIO, // 录音结束/答题结束（选择填空）
        END_LATS_AUDIO,//听说模考标准体系 最后音频播放
        END;// 考试结束
    }

    /**
     * Hanlder what
     */
    public class HandlerWhat {
        public static final int PLAY_SOUND = 101;// 播放音频

        public static final int UPDATE_TIME = 2;// 更新时间

        public static final int TOTAL_TIMER = 3;// 总计时

        public static final int AUDIO_PLAY_ERROR = 4;// 播放音频错误

        public static final int GET_SCORE_RESULT = 5;// 获取口头作文打分结果

    }

    /**
     * 计算填空题得分
     *
     * @param totalScore
     * @param count
     * @param index
     * @return
     */
    public static float calcFillBlankScore(float totalScore, int count,
                                           int index) {
        if (count <= 1) {
            return totalScore;
        }
        if (index > count - 1) {
            return 0;
        }
        BigDecimal scoreBd = new BigDecimal(totalScore);
        BigDecimal countBd = new BigDecimal(count);
        BigDecimal indexBd = new BigDecimal(index);
        BigDecimal avgScore = scoreBd.divide(countBd, 2,
                BigDecimal.ROUND_HALF_UP);
        BigDecimal result = index < count - 1 ? avgScore
                : scoreBd.subtract(indexBd.multiply(avgScore));
        return result.floatValue();

    }


    /**
     * 获取答案body,评测文本
     *
     * @param questions
     * @return
     */
    public static String getAnswerBody(Questions questions) {
        List<OptionInfo> options = questions.getOptions();
        if (options != null && !options.isEmpty()) {
            OptionInfo optionInfo = options.get(0);
            if (optionInfo.getIsAnswer() == OptionInfo.IsAnswer.IS_ANSWER_CORRECT) {

                List<OptionDetail> value = optionInfo.getValue();
                if (value != null && !value.isEmpty()) {
                    OptionDetail optionDetail = value.get(0);
                    String body = optionDetail.getBody();

                    if (null != body) {
                        //防止结尾多了"/n/n"换行符号
                        body = body.trim();
                    }

                    //模仿朗读时不需求过滤
//                    if (!TextUtils.isEmpty(body) && body.startsWith("{") && body.endsWith("}") && body.contains(ListenSpeakUtil.JSGF))
                    {
                        return body;
                    }
                }
            }
        }
        return null;
    }





    /**
     * 获取保存今日新学单词的KEY
     *
     * @return
     */
    public static String getCurrentNewWordKey() {

        return SerializableManager.SerializeKey.CURRENR_NEW_INDEX + "__" + EApplication.getInstance().getUserInfoBase().getUserId();
    }


    /**
     * 获取保存今日新学单词的KEY
     *
     * @return
     */
    public static String getCompleteTimeKey() {

        return SerializableManager.SerializeKey.WORD_COMPLETE_TIME + "__" + BaseDBManager.BOOK_ID + "__" + EApplication.getInstance().getUserInfoBase().getUserId();
    }

    public static String getCompleteTimeKey(int bookId) {

        return SerializableManager.SerializeKey.WORD_COMPLETE_TIME + "__" + bookId + "__" + EApplication.getInstance().getUserInfoBase().getUserId();
    }

    /**
     * 获取content_id
     *
     * @param questions
     * @return
     */
    public static String getContentId(Questions questions) {
        List<OptionInfo> options = questions.getOptions();
        if (options != null && !options.isEmpty()) {
            OptionInfo optionInfo = options.get(0);
            if (optionInfo
                    .getIsAnswer() == OptionInfo.IsAnswer.IS_ANSWER_CORRECT) {
                List<OptionDetail> value = optionInfo.getValue();
                if (value != null && !value.isEmpty()) {
                    OptionDetail optionDetail = value.get(0);
                    String contentId = optionDetail.getContent_id();
                    if (!TextUtils.isEmpty(contentId)) {
                        return contentId;
                        // return "MODULE_PAPER-000001-Test_QT-3.1";
                    }
                }
            }
        }
        return null;
    }


    /**
     * 取得阅题时间
     *
     * @param resourceDetailList
     * @param smallQues
     * @param bigQuesIndex
     * @return
     */
    public static int getLookTime(List<ResourceDetail> resourceDetailList, Questions smallQues, int bigQuesIndex) {
        int second = 0;
        QuestionRule listeningAndSpeakingRule = resourceDetailList
                .get(bigQuesIndex).getTemplateSettings()
                .getListeningAndSpeakingRule();
        second = smallQues.getType() == Questions.QuestionType.QUESTION_TYPE_READ ? listeningAndSpeakingRule.getRootLookTime()
                : listeningAndSpeakingRule.getLookTime();
        return second;

    }


    public static boolean isLastQuestion(List<ResourceDetail> mResourceList, int mBigQuesIndex, int mSmallQuesIndex, int mChildQuesIndex) {
        boolean isLastQues = false;
        //当前层级是否有子题，子题遍历，是否有小题，小题是否遍历完，大题遍历
        List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
        List<Questions> childQuesList = null;
        // 有小题
        if (smallQuesList != null && !smallQuesList.isEmpty() && mSmallQuesIndex < smallQuesList.size()) {
            childQuesList = smallQuesList.get(mSmallQuesIndex).getChildren();
        }
        if (childQuesList != null && !childQuesList.isEmpty() && mChildQuesIndex < childQuesList.size() - 1) // 且有子题
        {
            // 切换到 下一子题
//            switchChildQuestion(childQues,  mResourceList);
            return isLastQues;
        } else {
            //没有子题,或者子题遍历完
            if (smallQuesList != null && mSmallQuesIndex < smallQuesList.size() - 1) {// 下一小题
                mSmallQuesIndex++;
                return isLastQues;
            } else {
                if (mBigQuesIndex < mResourceList.size() - 1) {// 下一大题
                    //toNextBigQuestion(mResourceList);
                } else {// 结束考试
                    isLastQues = true;
                    return isLastQues;
                }
            }
        }
        return isLastQues;
    }


    /**
     * @param mResourceList
     * @param mBigQuesIndex
     * @param mSmallQuesIndex
     * @param mChildQuesIndex
     * @return 重做模式，每道大题最后一小题都是完成答题
     */

    public static boolean isLastQuestionOnRetryMode(List<ResourceDetail> mResourceList, int mBigQuesIndex, int mSmallQuesIndex, int mChildQuesIndex) {
        boolean isLastQues = false;
        //当前层级是否有子题，子题遍历，是否有小题，小题是否遍历完，大题遍历
        List<Questions> smallQuesList = mResourceList.get(mBigQuesIndex).getQuestions();
        List<Questions> childQuesList = null;
        // 有小题
        if (smallQuesList != null && !smallQuesList.isEmpty() && mSmallQuesIndex < smallQuesList.size()) {
            childQuesList = smallQuesList.get(mSmallQuesIndex).getChildren();
        }
        if (childQuesList != null && !childQuesList.isEmpty() && mChildQuesIndex < childQuesList.size() - 1) // 且有子题
        {
            // 切换到 下一子题
//            switchChildQuestion(childQues,  mResourceList);
            return isLastQues;
        } else {
            //没有子题,或者子题遍历完


            if (smallQuesList != null && mSmallQuesIndex < smallQuesList.size() - 1) {// 下一小题
                mSmallQuesIndex++;
                return isLastQues;
            } else {
                isLastQues = true;
                return isLastQues;

//                if (mBigQuesIndex < mResourceList.size() - 1) {// 下一大题
//                    //toNextBigQuestion(mResourceList);
//                } else {// 结束考试
//                    isLastQues=true;
//                    return isLastQues;
//                }
            }
        }
//        return  isLastQues;
    }

    public static boolean isOnLineAnswerOrListenSpeakOrInteractiveTutorial(int moduleId) {
        boolean bool = false;
        if (moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_ONLINE_ANSWER
                || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_INTERACTIVE_TUTORIAL
                || moduleId == ModuleInfo.ModuleInfoId.MODULE_ID_LISTEN_SPEAK_EXAM) {
            bool = true;
        }
        return bool;
    }

    /**
     * 当前计划每次计划单词个数
     *
     * @return
     */
    public static String getCurrentPlanWordCountKey() {
        return SerializableManager.SerializeKey.CURRENT_WORD_PLAN_COUNT + "__" + BaseDBManager.BOOK_ID + "__" + +EApplication.getInstance().getUserInfoBase().getUserId();
    }


    /**
     * @return
     */
    public static String getCurrentPlanBookIdKey() {
        return SerializableManager.SerializeKey.CURRENT_PLAIN_BOOK_ID + "__" + EApplication.getInstance().getUserInfoBase().getUserId();
    }

    /**
     * 子题题目分数
     *
     * @param childQuestion
     * @param scores
     */
    public static String getChildQuestionScore(Questions childQuestion, List<QuestionScore> scores) {
        String textScore = "";
        return textScore;
//        if (childQuestion != null && scores != null && scores.size() > 0) {
//            String versionId = childQuestion.getVersionId();
//            for (int i = 0; i < scores.size(); i++) {
//                QuestionScore item = scores.get(i);
//                if (versionId.equals(item.getQuestionVersionId())) {
//                    String score = "";
//                    if (DateUtils.isInteger(String.valueOf(item.getScore()))) {
//                        score = (int) item.getScore() + "";
//                    } else {
//                        score = String.valueOf(item.getScore());
//                    }
//                    textScore = "(" + score + "分)";
//                }
//            }
//        }
    }
}
